package com.blkj.iam.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blkj.iam.common.constant.StationConstants;
import com.blkj.iam.common.constant.StatusConstants;
import com.blkj.iam.common.constant.SystemConstants;
import com.blkj.iam.common.exception.BusinessException;
import com.blkj.iam.common.model.Option;
import com.blkj.iam.common.result.ApiResult;
import com.blkj.iam.common.util.PinyinUtils;
import com.blkj.iam.core.security.util.SecurityUtils;
import com.blkj.iam.system.converter.RoleConverter;
import com.blkj.iam.system.mapper.RoleMapper;
import com.blkj.iam.system.model.entity.Dept;
import com.blkj.iam.system.model.entity.Role;
import com.blkj.iam.system.model.entity.RoleMenu;
import com.blkj.iam.system.model.form.RoleForm;
import com.blkj.iam.system.model.form.RoleOptionsForm;
import com.blkj.iam.system.model.query.RolePageQuery;
import com.blkj.iam.system.model.vo.RolePageVO;
import com.blkj.iam.system.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色业务实现类
 *
 * @author haoxr
 * @since 2022/6/3
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMenuService roleMenuService;
    private final UserRoleService userRoleService;
    private final RoleConverter roleConverter;
    private final ServerDataSyncService dataSyncService;
    private final DeptService deptService;
    private final RoleMapper roleMapper;

    /**
     * 角色分页列表
     *
     * @param queryParams 角色查询参数
     * @return {@link Page<  RolePageVO  >} – 角色分页列表
     */
    @Override
    public Page<RolePageVO> getRolePage(RolePageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        Long tenantId = SecurityUtils.getUser().get().getTenantId();

        // 查询数据(非超级管理员不显示超级管理员角色)
        Page<Role> rolePage = this.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<Role>().and(wrapper -> wrapper.eq(Role::getTenantId, tenantId)).and(StrUtil.isNotBlank(keywords), wrapper -> wrapper.like(Role::getName, keywords).or().like(Role::getCode, keywords)).ne(!SecurityUtils.isRoot(), Role::getCode, SystemConstants.ROOT_ROLE_CODE).orderByAsc(Role::getSort).orderByDesc(Role::getCreateTime).orderByDesc(Role::getUpdateTime));

        // 实体转换
        return roleConverter.toPageVo(rolePage);
    }

    /**
     * 角色下拉列表
     *
     * @return {@link List<Option>} – 角色下拉列表
     */
    @Override
    public List<Option<Long>> listRoleOptions() {
        // 查询数据
        Long tenantId = SecurityUtils.getUser().get().getTenantId();
        List<Role> roleList = this.list(new LambdaQueryWrapper<Role>().eq(Role::getTenantId, tenantId).ne(!SecurityUtils.isRoot(), Role::getCode, SystemConstants.ROOT_ROLE_CODE).select(Role::getId, Role::getName).orderByAsc(Role::getSort));

        // 实体转换
        return roleConverter.toOptions(roleList);
    }

    /**
     * 保存角色
     *
     * @param roleForm 角色表单数据
     * @return {@link Boolean}
     */
    @Override
    public boolean saveRole(RoleForm roleForm) {
        Long roleId = roleForm.getId();

        // 编辑角色时，判断角色是否存在
        Role oldRole = null;
        if (roleId != null) {
            oldRole = this.getById(roleId);
            Assert.isTrue(oldRole != null, "角色不存在");
        }

        String roleCode = roleForm.getCode();
        if (ObjectUtil.isEmpty(roleCode)) {
            roleCode = PinyinUtils.toPinyinAbbreviation(roleForm.getName());
        }
        String finalRoleCode = roleCode;
        roleForm.setCode(finalRoleCode);
        long count = this.count(new LambdaQueryWrapper<Role>().ne(roleId != null, Role::getId, roleId).and(wrapper -> wrapper.eq(Role::getCode, finalRoleCode).or().eq(Role::getName, roleForm.getName())));
        Assert.isTrue(count == 0, "角色名称或角色编码已存在，请修改后重试！");

        // 实体转换
        Role role = roleConverter.toEntity(roleForm);

        // 设置其他信息
        Dept dept = deptService.getById(roleForm.getDeptId());
        if (ObjectUtil.isNotEmpty(roleForm.getDeptId())) {
            role.setType(StatusConstants.ENABLE);
            role.setRoleType(StatusConstants.ENABLE);
            role.setItemType(Integer.valueOf(dept.getDepartType()));
        } else {
            role.setType(StatusConstants.DISABLE);
            role.setRoleType(StatusConstants.DISABLE);
        }

        if (dept.getDepartType().equals(StatusConstants.DISABLE_STR)) {
            role.setRoleType(StatusConstants.DISABLE);
        }
        role.setDepartId(dept.getIdStr());
        role.setDepartName(dept.getName());
        role.setSysOrgCode(dept.getCode());
        role.setCreateUser(SecurityUtils.getUsername());
        role.setCreateBy(SecurityUtils.getUserId());

        // 获取当前用户的租户
        Long tenantId = SecurityUtils.getUser().get().getTenantId();
        role.setTenantId(tenantId);

        boolean result = this.saveOrUpdate(role);
        if (result) {
            // 判断角色编码或状态是否修改，修改了则刷新权限缓存
            if (oldRole != null && (!StrUtil.equals(oldRole.getCode(), roleCode) || !ObjectUtil.equals(oldRole.getStatus(), roleForm.getStatus()))) {
                roleMenuService.refreshRolePermsCache(oldRole.getCode(), roleCode);
            }

            // 同步数据到客户端
            Long formId = roleForm.getId();
            if (formId == null) {
                dataSyncService.addRole(role);
            } else {
                dataSyncService.editRole(role);
            }
        }

        return result;
    }

    /**
     * 获取角色表单数据
     *
     * @param roleId 角色ID
     * @return {@link RoleForm} – 角色表单数据
     */
    @Override
    public RoleForm getRoleForm(Long roleId) {
        Role entity = this.getById(roleId);
        RoleForm roleForm = roleConverter.toForm(entity);
        Dept dept = deptService.getOne(new LambdaQueryWrapper<Dept>().eq(Dept::getIdStr, entity.getDepartId()));
        if (ObjectUtil.isEmpty(dept)) {
            dept = deptService.getById(entity.getDepartId());
        }
        if (ObjectUtil.isNotEmpty(dept)) {
            roleForm.setDeptType(Integer.valueOf(dept.getDepartType()));
            roleForm.setDeptId(dept.getId());
            roleForm.setDeptName(dept.getName());
        }
        return roleForm;
    }

    /**
     * 修改角色状态
     *
     * @param roleId 角色ID
     * @param status 角色状态(1:启用；0:禁用)
     * @return {@link Boolean}
     */
    @Override
    public boolean updateRoleStatus(Long roleId, Integer status) {

        Role role = this.getById(roleId);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }

        role.setStatus(status);
        boolean result = this.updateById(role);
        if (result) {
            // 刷新角色的权限缓存
            roleMenuService.refreshRolePermsCache(role.getCode());
        }
        return result;
    }

    /**
     * 批量删除角色
     *
     * @param ids 角色ID，多个使用英文逗号(,)分割
     */
    @Override
    public void deleteRoles(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的角色ID不能为空");
        List<Long> roleIds = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();

        for (Long roleId : roleIds) {
            Role role = this.getById(roleId);
            Assert.isTrue(role != null, "角色不存在");

            // 判断角色是否被用户关联
            boolean isRoleAssigned = userRoleService.hasAssignedUsers(roleId);
            Assert.isTrue(!isRoleAssigned, "角色【{}】已分配用户，请先解除关联后删除", role.getName());

            // 同步数据到客户端
            ApiResult<Object> result = dataSyncService.deleteRole(role);
            if (result.getCode() == HttpStatus.HTTP_OK) {
                boolean deleteResult = roleMapper.delete(new LambdaQueryWrapper<Role>().eq(Role::getId, roleId)) > 0;
                if (deleteResult) {
                    // 删除成功，刷新权限缓存
                    roleMenuService.refreshRolePermsCache(role.getCode());
                }
            }
        }
    }

    /**
     * 获取角色的菜单ID集合
     *
     * @param roleId 角色ID
     * @return 菜单ID集合(包括按钮权限ID)
     */
    @Override
    public List<Long> getRoleMenuIds(Long roleId) {
        return roleMenuService.listMenuIdsByRoleId(roleId);
    }

    /**
     * 修改角色的资源权限
     *
     * @param roleId  角色ID
     * @param menuIds 菜单ID集合
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = "menu", key = "'routes'")
    public void assignMenusToRole(Long roleId, List<Long> menuIds) {
        Role role = this.getById(roleId);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }
        // 删除角色菜单
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));

        // 新增角色菜单
        if (CollectionUtil.isNotEmpty(menuIds)) {
            // 获取当前用户的租户
            Long tenantId = SecurityUtils.getUser().get().getTenantId();
            int batchSize = 500;
            for (int i = 0; i < menuIds.size(); i += batchSize) {
                List<Long> batchMenuIds = menuIds.subList(i, Math.min(i + batchSize, menuIds.size()));
                List<RoleMenu> menuList = batchMenuIds.parallelStream().map(menuId -> new RoleMenu(roleId, menuId, tenantId)).collect(Collectors.toList());
                roleMenuService.saveBatch(menuList);
            }
        }

        // 刷新角色的权限缓存
        roleMenuService.refreshRolePermsCache(role.getCode());
    }

    /**
     * 获取最大范围的数据权限
     *
     * @param roles 角色编码集合
     * @return {@link Integer} – 数据权限范围
     */
    @Override
    public Integer getMaximumDataScope(Set<String> roles) {
        Integer dataScope = this.baseMapper.getMaximumDataScope(roles);
        return dataScope;
    }

    /**
     * 根据部门ID角色下拉列表
     *
     * @param optionsForm
     * @return
     */
    @Override
    public List<Option<Long>> listParamsRoleOptions(RoleOptionsForm optionsForm) {
        // 查询数据
        Long tenantId = SecurityUtils.getUser().get().getTenantId();
        Dept dept = deptService.getById(optionsForm.getDeptId());
        List<Role> roleList = this.list(new LambdaQueryWrapper<Role>().eq(Role::getDepartId, dept.getIdStr()).eq(Role::getTenantId, tenantId).ne(!SecurityUtils.isRoot(), Role::getCode, SystemConstants.ROOT_ROLE_CODE).select(Role::getId, Role::getName).orderByAsc(Role::getSort));
        if (ObjectUtil.isNotEmpty(optionsForm.getRoleIds())) {
            List<Role> roleList1 = this.list(new LambdaQueryWrapper<Role>().eq(Role::getTenantId, tenantId).in(Role::getId, optionsForm.getRoleIds()).select(Role::getId, Role::getName));
            roleList.addAll(roleList1);
        }

        // 去重
        List<Role> distinctRoleList = roleList.stream().distinct().collect(Collectors.toList());

        // 实体转换
        return roleConverter.toOptions(distinctRoleList);
    }

    /**
     * 场站角色分页列表
     *
     * @param queryParams
     * @return
     */
    @Override
    public Page<RolePageVO> getStationRolePage(RolePageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        Long tenantId = SecurityUtils.getUser().get().getTenantId();
        Integer deptType = queryParams.getDeptType();

        List<Integer> paramsList = new ArrayList<>();
        paramsList.add(StationConstants.MERCHANT);
        paramsList.add(StationConstants.SUPPLIER);
        paramsList.add(StationConstants.CARRIER);

        // 查询数据(非超级管理员不显示超级管理员角色)
        Page<Role> rolePage = this.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<Role>().and(wrapper -> wrapper.eq(Role::getTenantId, tenantId)).in(Role::getItemType, paramsList).eq(ObjectUtil.isNotEmpty(deptType), Role::getItemType, deptType).and(StrUtil.isNotBlank(keywords), wrapper -> wrapper.like(Role::getName, keywords).or().like(Role::getCode, keywords)).ne(!SecurityUtils.isRoot(), Role::getCode, SystemConstants.ROOT_ROLE_CODE).orderByAsc(Role::getSort).orderByDesc(Role::getCreateTime).orderByDesc(Role::getUpdateTime));

        // 实体转换
        return roleConverter.toPageVo(rolePage);
    }

}
